import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';


void main() {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    systemNavigationBarColor: Colors.white,
    systemNavigationBarIconBrightness: Brightness.dark,
  ));
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  ScrollController _controller;
  TabController _tabController;

  //宝贝、评价、详情、推荐4个模块分别设置一个key
  List<GlobalKey> keys = [];
  double key0height ;
  double key1height ;
  double key2height ;
  int childCount = 25;
  @override
  void initState() {
    super.initState();
    keys.add(GlobalKey());
    keys.add(GlobalKey());
    keys.add(GlobalKey());
    keys.add(GlobalKey());
    _controller = ScrollController();
    _tabController = TabController(length: 4, vsync: this);
    //监听ScrollController的滑动
    _controller.addListener(() {
        //选择
        if(key0height == null ){
          key0height = _getHeiget(0);
          print("key0height = $key0height");
        }
        if(key1height == null ){
          key1height = key0height + _getHeiget(1);
          print("key1height = $key1height");
        }
        if(key2height == null ){
          key2height = key1height + _getHeiget(2);
          print("key2height = $key2height");
        }
        if( _controller.offset < key0height){
          _tabController.animateTo(0);
        }else if(_controller.offset >= key0height && _controller.offset < key1height){
          _tabController.animateTo(1);
        }else if(_controller.offset >= key1height && _controller.offset < key2height){
          _tabController.animateTo(2);
        }else{
          _tabController.animateTo(3);
        }
    });
  }

  @override
  void dispose() {
    //为了避免内存泄露，需要调用_controller.dispose
    _controller?.dispose();
    _tabController?.dispose();
    super.dispose();
  }

  //获取key对应的widget的高度
  double _getHeiget(int i) {
    double height = 0;
    RenderObject renderObject= keys[i]?.currentContext?.findRenderObject();
    if(renderObject is RenderSliverToBoxAdapter){
      height = renderObject?.child?.size?.height??0.0;
    }else if(renderObject is RenderSliverFixedExtentList){
      //?????RenderSliverFixedExtentList中的childCount=19？我明明设置的20啊。
      height = childCount*renderObject.itemExtent;
    }else{
      //如果用到其他RenderObject的子类这里需要加逻辑，
      print('==============');
    }
    return height;
  }

  @override
  Widget build(BuildContext buildContext) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
        bottom: PreferredSize(
            preferredSize: Size.fromHeight(48),
            child: Container(
              height: 48,
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              color: Colors.white,
              child: TabBar(
                isScrollable: true,
                controller: _tabController,
                labelColor: Colors.black,
                unselectedLabelColor: Color.fromARGB(255, 111, 111, 111),
                indicatorColor: Colors.black,
                tabs: [
                  Container(
                    height: 48,
                    alignment: Alignment.center,
                    child: Text('宝贝'),
                  ),
                  Text('评价'),
                  Text('详情'),
                  Text('推荐')
                ],
                onTap: (index) {
                  //通关循环计算offset
                  double height = 0;
                  for(int i = 0;i <index;i++){
                    height += _getHeiget(i);
                  }
                  _controller?.animateTo(height.toDouble(),
                      duration: Duration(milliseconds: 200),
                      curve: Curves.linear);
                },
              ),
            )),
      ),
      body: CustomScrollView(
        controller: _controller,
        scrollDirection: Axis.vertical,
        slivers: <Widget>[
          //宝贝
          SliverToBoxAdapter(
            key: keys[0],
            child: Container(
              color: Colors.red,
              alignment: Alignment.center,
              child: Image.network('https://pic.netbian.com/uploads/allimg/180826/113958-1535254798fc1c.jpg'
                  ,fit: BoxFit.cover),
            ),
          ),
          //评价
          SliverToBoxAdapter(
            key: keys[1],
            child: Container(
              height: 200,
              color: Colors.green,
              alignment: Alignment.center,
              child: Text('宝贝评价',style: TextStyle(color: Colors.white)),
            ),
          ),
          //详情
          SliverFixedExtentList(
              key: keys[2],
              delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                return Container(
                  alignment: Alignment.center,
                  child: Text(
                    '详情图片$index',
                    textAlign: TextAlign.center,
                  ),
                );
              }, childCount: childCount),
              itemExtent: 100),
          //推荐
          SliverFillRemaining(
            key: keys[3],
            child: Container(
              height: 693,
              color: Colors.blue,
              alignment: Alignment.topCenter,
              child: Text('宝贝推荐',style: TextStyle(color: Colors.white)),
            ),
          ),
        ],
      ),
    );
  }
}


